package com.zjq.authoritysystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zjq.authoritysystem.entity.Department;
import com.zjq.authoritysystem.mapper.DepartmentMapper;
import com.zjq.authoritysystem.service.DepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjq.authoritysystem.utils.DepartmentTreeUtil;
import com.zjq.authoritysystem.vo.query.DepartmentQueryVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author BetOnMe
 * @since 2023-09-18
 */
@Service
@Transactional
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Override
    public List<Department> findDepartmentList(DepartmentQueryVo departmentQueryVo) {
        List<Department> departments = this.list(new QueryWrapper<Department>()
                .like(!ObjectUtils.isEmpty(departmentQueryVo.getName()), "name", departmentQueryVo.getName())
                .eq("is_delete", Department.IS_DELETE_NO)
                .orderByDesc("sort"));
        List<Department> departmentList = DepartmentTreeUtil.makeDepartmentTree(departments, Department.PARENT_ID_TOP);
        return departmentList;
    }

    @Override
    public List<Department> getParentDepartment() {
        List<Department> departmentList = this.list(new QueryWrapper<Department>()
                .eq("is_delete", Department.IS_DELETE_NO)
                .orderByAsc("sort"));
        Department department = new Department();
        department.setId(0);
        department.setParentId(-1);
        department.setName("顶级部门");
        department.setSort(-1);
        departmentList.add(department);
        Collections.sort(departmentList, Comparator.comparingInt(Department::getSort));
        return departmentList;
    }

    @Override
    public Boolean deleteById(Integer id) {
        return this.update(new UpdateWrapper<Department>()
                .set("is_delete", Department.IS_DELETE_YES)
                .eq("id", id)
                .eq("is_delete", Department.IS_DELETE_NO));
    }

    @Override
    public List<Department> getByParentId(Integer id) {
        List<Department> departments = this.list(new QueryWrapper<Department>().eq("parent_id", id));
        return departments;
    }
}
